package health.lm.com.component_base.popup.share;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import health.lm.com.component_base.R;
import health.lm.com.component_base.popup.model.PopupModel;
import health.lm.com.component_base.widget.CustomPopWindow;
import health.lm.com.network.callback.SimpleCallBack;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

import static health.lm.com.component_base.helper.ImageLoaderHelper.IMG_ERROR;


/**
 * Created by Android Studio .
 * 作者：zhong
 * 日期：2019/2/23
 * 邮箱：15206394364@163.com
 * 介绍：
 * 修订：====================
 */
public class ShareProductUtil implements View.OnClickListener {
    private static ShareProductUtil productUtil;
    private static Context ctx;
    private CustomPopWindow popWindow;
    private String url;
    private String title;
    private String description;
    private String avatar;
    private View mRvHome;
    private int shareType = 0;
    private String newsId;

    private UMShareListener shareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            popWindow.dissmiss();
            //if (shareType == SHARE_TYPE_POSTER) return;
            //ToastUtils.showShort("成功了");
            //newsShareResult();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtils.showShort("分享失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtils.showShort("分享取消");
        }
    };
    private ImageView img;
    private View contentView;

    public static ShareProductUtil getInstance() {
        if (productUtil == null)
            productUtil = new ShareProductUtil();
        return productUtil;
    }

    /**
     * 显示popwindow
     */
    public void show(Context context, View mLayoutPopup, String id) {
        this.newsId = id;
        this.mRvHome = mLayoutPopup;
        ctx = context;
        this.contentView = LayoutInflater.from(context).inflate(R.layout.pop_share, null);
        //图片
        img = contentView.findViewById(R.id.iv_img);
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int heigth = dm.heightPixels;
        int width = dm.widthPixels;
        ViewGroup.LayoutParams lp = img.getLayoutParams();
        lp.width = width;
        lp.height = LinearLayout.LayoutParams.WRAP_CONTENT;
        img.setLayoutParams(lp);
        img.setMaxWidth(width);
        img.setMaxHeight(heigth * 3);
        img.setMinimumHeight(heigth);

        //ImageLoaderHelper.getInstance().load(context, TestImgEntity.img1, img);
        //微信
        TextView wx = contentView.findViewById(R.id.tv_wx);
        wx.setOnClickListener(this);
        //QQ
        TextView qq = contentView.findViewById(R.id.tv_qq);
        qq.setOnClickListener(this);
        //朋友圈
        TextView pyq = contentView.findViewById(R.id.tv_pyq);
        pyq.setOnClickListener(this);
        //取消
        TextView cancle = contentView.findViewById(R.id.tv_cancle);
        cancle.setOnClickListener(this);
        PopupModel.getInstance().shareProduct(id, new SimpleCallBack<SharePopBean>() {
            @Override
            public void onSuccess(SharePopBean pSharePopBean) {
                url = pSharePopBean.getImg_url();
                Glide.with(context).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@android.support.annotation.NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int imageHeight = resource.getHeight();
                        RequestOptions options = new RequestOptions()
                                .placeholder(R.drawable.ic_image_loading)  //加载中显示的图片
                                //.centerCrop()            //图像则位于视图的中央
                                // .override(1090, 1090*3/4)
                                .dontAnimate()
                                .error(IMG_ERROR) //加载失败时显示的图片centerCrop().
                                .diskCacheStrategy(DiskCacheStrategy.ALL);  //图片缓存
                        if (imageHeight > 4096) {
                            imageHeight = 4096;
                            ViewGroup.LayoutParams layoutParams = img.getLayoutParams();
                            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                            layoutParams.height = imageHeight;
                            img.setLayoutParams(layoutParams);
                            //ImageLoaderHelper.getInstance().load(context, resource, img);
                            Glide.with(context).load(resource).apply(options).into(img);
                        } else {
                            Glide.with(context).load(resource).apply(options).into(img);
                        }
                    }
                });
                //创建并显示popWindow
                //显示大小
                showPop();
            }
        });
    }

    private void showPop() {
        popWindow = new CustomPopWindow.PopupWindowBuilder(ctx)
                .setView(contentView)
                .enableBackgroundDark(true)
                .setBgDarkAlpha(0.7f)
                .setAnimationStyle(R.style.pop_bottom_anim)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
                .create()
                .showAtLocation(mRvHome, Gravity.BOTTOM, 0, 0);
    }

    //private void newsShareResult() {
    //    if (null == newsId || newsId.equals("")) return;
    //    NewsModel.getInstance().ProductShareResult(newsId, new BaseObserver<BaseResponse<UpLevelBean>, UpLevelBean>(baseView, false) {
    //        @Override
    //        protected void onSuccess(UpLevelBean entity) {
    //            //判断是否升级 弹窗
    //            UpLevelPopUtil.getInstance().init(ctx, mRvHome, baseView);
    //            //分享获得糖果通知弹窗
    //            if (entity.getStatus().equals("0")) return;
    //            NoticePopUtil.getInstance().showShare(ctx, mRvHome, entity);
    //        }
    //    });
    //}

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_wx) shareType(SHARE_MEDIA.WEIXIN);
        else if (v.getId() == R.id.tv_qq) shareType(SHARE_MEDIA.QQ);
        else if (v.getId() == R.id.tv_pyq) shareType(SHARE_MEDIA.WEIXIN_CIRCLE);
        else if (v.getId() == R.id.tv_cancle) popWindow.dissmiss();
//        switch (v.getId()) {
//            case R.id.tv_wx://微信
//                shareType(SHARE_MEDIA.WEIXIN);
////                RxView.clicks(v).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
////                    if (shareType == SHARE_TYPE_CONTENT) {
////                        shareContextType(SHARE_MEDIA.WEIXIN);
////                        return;
////                    }
////                    shareType(SHARE_MEDIA.WEIXIN);
////                });
//                break;
//            case R.id.tv_qq://qq
//                shareType(SHARE_MEDIA.QQ);
////                RxView.clicks(v).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
////                    if (shareType == SHARE_TYPE_CONTENT) {
////                        shareContextType(SHARE_MEDIA.QQ);
////                        return;
////                    }
////                    shareType(SHARE_MEDIA.QQ);
////                });
//                break;
//            case R.id.tv_pyq://朋友圈
//                shareType(SHARE_MEDIA.WEIXIN_CIRCLE);
////                RxView.clicks(v).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
////                    if (shareType == SHARE_TYPE_CONTENT) {
////                        shareContextType(SHARE_MEDIA.WEIXIN_CIRCLE);
////                        return;
////                    }
////                    shareType(SHARE_MEDIA.WEIXIN_CIRCLE);
////                });
//                break;
//            case R.id.tv_cancle://取消
//                popWindow.dissmiss();
//                break;
//        }
        //此处目的：https://developer.umeng.com/docs/66632/detail/66948?um_channel=sdk
        //重复调用了onPause 、onResume，以此判断
        if (/*shareType == SHARE_TYPE_POSTER && */null != popWindow) popWindow.dissmiss();
    }

    private void shareType(SHARE_MEDIA type) {
        new RxPermissions((Activity) ctx).requestEachCombined(Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Consumer<Permission>() {
            @Override
            public void accept(@NonNull Permission permission) throws Exception {
                if (permission.granted) {
                    UMImage imageurl = new UMImage(ctx, url);
                    imageurl.setThumb(new UMImage(ctx, R.mipmap.ic_launcher));
                    new ShareAction(((Activity) ctx)).withMedia(imageurl)
                            .setPlatform(type)
                            .setCallback(shareListener).share();
                } else if (permission.shouldShowRequestPermissionRationale) {
                    //拒绝权限请求
                    ToastUtils.showShort("请开启相机和读写手机存储权限");
                } else {
                    // 拒绝权限请求,并不再询问
                    // 可以提醒用户进入设置界面去设置权限
                    ToastUtils.showShort("已拒绝相机和读写手机存储权限，请到设置页面开启权限");
                }
            }
        });
    }
}
